package com.scau.phr.common.advices;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.scau.phr.common.domain.ApiResult;
import com.scau.phr.common.exceptions.ErrorCode;
import com.scau.phr.common.exceptions.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.support.WebExchangeBindException;

/**
 * RestController异常处理拦截器
 * 当RestController出现异常的时候，会将异常信息转化成对应的ApiResult返回给前端
 * @author yuzhiyi
 * @date 2018/7/9 10:51
 */
@ControllerAdvice(annotations = {
        RestController.class
})
public class ControllerExceptionHandler{

    private Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);
    /**
     * 处理参数错误的处理器
     */
    @ExceptionHandler({
            IllegalArgumentException.class,
    })
    @ResponseBody
    private ApiResult handleIllegalParamsException(Exception e){
        ErrorCode code = ErrorCode.PARAMS_ERROR;
        String message = e.getMessage();
        return new ApiResult(code.getCode(),message);
    }

    /**
     * 处理@Vaild错误的处理器
     * @param exception 参数异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public ApiResult handlerValidParamException(BindException exception){
        System.out.println("here");
        String message = exception.getFieldError().getDefaultMessage();
        return ApiResult.errorOf(ErrorCode.PARAMS_ERROR,message);
    }


    /**
     * 业务逻辑错误处理器
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    private ApiResult handleServiceException(Exception e){
        ApiResult res;
        if (e instanceof ServiceException){
            ServiceException serviceException = (ServiceException)e;
            int code = serviceException.getErrorCode().getCode();
            String msg = serviceException.getMessage();
            Object value = serviceException.getValue();
            res = new ApiResult(code,msg,value);
        }else{
            res = new ApiResult(ErrorCode.SERVER_ERROR.getCode(),"服务器错误");
        }
        return res;
    }

    /**
     * 处理其他错误的类，为了debug方便，会将异常打印出来
     * @param e 异常实例
     * @return  返回
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    private ApiResult handleOtherException(Exception e){
        logger.error(e.getMessage());
        e.printStackTrace();
        return new ApiResult(ErrorCode.SERVER_ERROR.getCode(),"服务器错误");
    }


}
